package com.itheima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.search.service.GoodsService;
import com.itheima.search.vo.DataInfo;
import com.itheima.search.vo.GoodsInfo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    RestHighLevelClient client;

    private final String GOODS_SYNC_DATABASE = "goodsinfo";

    @Override
    public String selectGoods(Map<String, String> condition) {
        if (!isSignificant(condition)){
            return null;
        }
        // 创建SearchRequest对象，并制定索引库名称
        SearchRequest request = new SearchRequest(GOODS_SYNC_DATABASE);

        // 创建SearchSourceBuilder对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 布尔查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        //拼接条件
        builderQuery(queryBuilder,condition);

        sourceBuilder.query(queryBuilder);

        //聚合分桶
        sourceBuilder.aggregation(AggregationBuilders.terms("brand").field("brandName"))
                .aggregation(AggregationBuilders.terms("category").field("categoryName"));

        int page = 1, size = 10;
        int from = (page - 1) * size;
        sourceBuilder.from(from);
        sourceBuilder.size(size);

        request.source(sourceBuilder);

        return loadData(request);
    }

    //封装查询数据
    private String loadData(SearchRequest request){
        DataInfo dataInfo = new DataInfo();
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Aggregations aggregations = response.getAggregations();

            Terms termsBrand = aggregations.get("brand");

            dataInfo.setBrandList(polyBucket(termsBrand));

            Terms termsCategory = aggregations.get("category");

            dataInfo.setCategoryList(polyBucket(termsCategory));

            // 5.解析结果
            SearchHits searchHits = response.getHits();
            //  5.1.获取总条数
            //long total = searchHits.getTotalHits().value;
            //  5.2.获取SearchHits数组，并遍历
            SearchHit[] hits = searchHits.getHits();
            List<GoodsInfo> goodsInfoList = new ArrayList<>();
            for (SearchHit hit : hits) {
                GoodsInfo goodsInfo = JSON.parseObject(hit.getSourceAsString(), GoodsInfo.class);
                goodsInfoList.add(goodsInfo);
            }
            dataInfo.setGoodsList(goodsInfoList);
            String str = JSON.toJSONString(dataInfo);
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //装载桶名
    private List<String> polyBucket(Terms terms) {
        List<? extends Terms.Bucket> buckets = terms.getBuckets();

        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String asString = bucket.getKeyAsString();
            list.add(asString);
        }
        return list;
    }

    private boolean isSignificant(Map<String, String> condition){

        if (condition==null&&condition.isEmpty()) {
            return false;
        }
        String[] keys = {"goods_name","min_price","max_price"};

        for (String key : keys) {
            if(condition.containsKey(key)){
                return true;
            }
        }
        return false;
    }

    //拼接条件
    private void builderQuery(BoolQueryBuilder queryBuilder, Map<String, String> condition) {
        String name = condition.get("goods_name");
        if (StringUtils.isNotBlank(name)) {
            queryBuilder.must(QueryBuilders
                    .matchQuery("name", name));
        }

        String minPrice = condition.get("min_price");
        if (StringUtils.isNotBlank(minPrice)) {
            queryBuilder.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(minPrice));
        }

        String maxPrice = condition.get("max_price");
        if (StringUtils.isNotBlank(maxPrice)) {
            queryBuilder.filter(QueryBuilders
                    .rangeQuery("price")
                    .lte(maxPrice));
        }

/*        String brand = condition.get("goods_name");
        if (StringUtils.isNotBlank(name)) {
            queryBuilder.must(QueryBuilders
                    .matchQuery("name", name));
        }*/
    }
}
